package org.six.background.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.six.background.config.ImitateRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class LoginAop {
    @Autowired
    private ImitateRedis imitateRedis;

    @Pointcut("execution(* org.six.background.controller.UserController.selectById(..))"+
            "execution(* org.six.background.controller.*.*(..))"+
            "execution(* org.six.background.controller.UserController.test(..))")
    public void loginPointcut(){
    }

    @Around("loginPointcut()")
    public Object logyz(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("进入增强方法");
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=servletRequestAttributes.getRequest();
        String usid=request.getHeader("usid");
        String token=request.getHeader("tokenStr");
        Map map=new HashMap();
        if (usid==null&&token==null){
            map.put("code","0");
            map.put("message","暂未登陆");
            return map;
        }else {
            int i=SignUpYZ(usid,token);
            if (i==0){
                map.put("code","0");
                map.put("message","暂未登陆");
                return map;
            }else if (i==1){
                map.put("code","1");
                map.put("message","登录失效");
                return map;
            }
            else if (i==2){
                map.put("code","2");
                map.put("message","登录过期");
                return map;
            }else{
                //成功---继续往后执行
                //joinPoint.proceed()：执行原有方法
                return joinPoint.proceed();
            }
        }
    }

    public int SignUpYZ(String usid,String token){
        Map<String, Map> loginMap=imitateRedis.getLoginMap();
        if(loginMap.get(usid)==null){
            return 0;//未登录
        }
        if(!loginMap.get(usid).get("token").equals(token)){
            //两次token不同
            return 1;//无效登录
        }
        //验证是否过期---10秒
        Date date=new Date();//当前系统时间
        long cha=date.getTime()-(long)(loginMap.get(usid).get("oldTime"));
        if(cha>5*60*1000){
            return 2;//登录过期
        }
        return 3;//没问题
    }


}
